package com.colin.aiyi.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.colin.aiyi.R;
import com.colin.aiyi.app.Constant;
import com.colin.aiyi.entity.User;
import com.colin.aiyi.entity.WXRequest;
import com.colin.aiyi.entity.WXResponse;
import com.colin.aiyi.entity.response.BaseResponse;
import com.colin.aiyi.entity.response.LoginResponse;
import com.colin.aiyi.entity.response.UserInfoResponse;
import com.colin.aiyi.ui.registerwx.ImpPRegisterWX;
import com.colin.aiyi.ui.Home.MainActivity;
import com.colin.aiyi.utils.SharePreferenceUtil;
import com.colin.aiyi.utils.TimeUtil;
import com.colin.aiyi.utils.VerifyUtil;
import com.colin.aiyi.view.ShowMsgUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by hl on 2017/5/22.
 */

public class RegisterWxAc extends BaseActivity implements TimeUtil.TimeDownEvent {
    @BindView(R.id.img_logo)
    ImageView imgLogo;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.edit_vcode)
    EditText editVcode;
    @BindView(R.id.text_vcode)
    TextView textVcode;
    @BindView(R.id.text_send)
    TextView textSend;
    @BindView(R.id.text_msg)
    TextView textMsg;
    boolean flagTime = true;
    WXRequest request = new WXRequest();
    @BindView(R.id.text_banner_left)
    TextView textBannerLeft;
    @BindView(R.id.text_banner_title)
    TextView textBannerTitle;
    @BindView(R.id.text_banner_rigth)
    TextView textBannerRigth;
    @BindView(R.id.linear)
    LinearLayout linear;
    @BindView(R.id.linear_base)
    LinearLayout linearBase;
    private WXResponse wxRespone;

    /*  步骤，获取openid，检测openid是否绑定，绑定，个人（登）录信息*/
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_register_wx);
        ButterKnife.bind(this);
        textBannerLeft.setOnClickListener(this);
        textBannerTitle.setText("");
        linear.setBackgroundColor(Color.alpha(100));
        String code = getIntent().getStringExtra("code");
        iPresenter = new ImpPRegisterWX();
        request.setCode(code);
        iPresenter.getOpenId(request);
        linearBase.setVisibility(View.INVISIBLE);
        ShowMsgUtil.showLoadingDialog(this);
    }

    @OnClick({R.id.text_vcode, R.id.text_send})
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.text_vcode:
                if (!VerifyUtil.checkTextValueRight(
                        new TextView[]{editPhone},
                        new String[]{"请输入正确手机号"},
                        new String[]{VerifyUtil.EX_PHONE},
                        textMsg)) {
                    return;
                }
                if (flagTime) {
                    TimeUtil.timeDown(Constant.TIMER, this);
                    flagTime = false;
                }

                request.setTelNo(editPhone.getText().toString());
                request.setLoginType("weixin");
                request.setOpenId(wxRespone.getOpenid());
                iPresenter.bind_sendCode(request);

                break;
            case R.id.edit_phone:
                break;
            case R.id.text_send:
                if (!VerifyUtil.checkTextValueRight(
                        new TextView[]{editPhone},
                        new String[]{"请输入正确手机号"},
                        new String[]{VerifyUtil.EX_PHONE},
                        textMsg)) {
                    break;
                }
                if (!VerifyUtil.checkEmptiy(editVcode)) {
                    textMsg.setText("请输入验证码");
                    break;
                }
                request.setTelNo(editPhone.getText().toString());
                request.setOpenId(wxRespone.getOpenid());
                request.setMessageCode(editVcode.getText().toString());
                iPresenter.login_out_bind(request);


                break;
        }
    }

    @Subscribe
    public void checkResponse(BaseResponse response) {
        if (response.getCode() == 200) {
            if (response.getMsgType() == Constant.CODE_bind_sendCode) {
                showMsg("验证码已发到手机" + editPhone.getText().toString());
            }
        }
    }

    /*获取个人信息*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getUerInfo(UserInfoResponse user) {
        if (user.getCode() == 200) {
            SharePreferenceUtil.saveObject(this, user.getData());
            JPushInterface.setAlias(this, user.getData().getTelNo(), new TagAliasCallback() {
                @Override
                public void gotResult(int i, String s, Set<String> set) {
                    System.out.println("设置别名返回结果："+i);
                }
            });
            goToMain();
        } else {
            SharePreferenceUtil.saveObject(this, User.getInstance());
        }
    }


    private void goToMain() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }

    /*检查openid是否绑定  未绑定*/
    @Subscribe
    public void checkResponse(LoginResponse response) {
        ShowMsgUtil.hideLoadingDialog();
        linearBase.setVisibility(View.VISIBLE);
    }

    /* 拉去openid */
    @Subscribe
    public void checkResponse(WXResponse response) {
        ShowMsgUtil.hideLoadingDialog();
        if (response != null) {
            if (response.getOpenid() != null) {
                this.wxRespone = response;
                return;
            }
        }
        showMsg("获取登录信息失败");
        finish();


    }


    @Override
    public void timeDown(int indexTime) {
        if (indexTime == -1) {
            flagTime = true;
            textVcode.setText("发送");
            return;
        }
        indexTime = Constant.TIMER - indexTime;
        indexTime = indexTime / 1000;
        textVcode.setText(indexTime + "秒");
    }


}
